package com.company.game01;

import cn.hutool.core.util.ReflectUtil;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class ObjectPool<T> {
    private List<T> POOL = Collections.synchronizedList(new LinkedList<>());
    private int initPoolSize = 10;
    private int maxPoolSize = 100;
    private Class<T> clazz;

    private void init(Class<T> clazz) {
        for (int i = 0; i < initPoolSize; i++) {
            T t = ReflectUtil.newInstance(clazz);
            POOL.add(t);
        }
    }

    public ObjectPool(Class<T> clazz) {
        this.clazz = clazz;
        init(clazz);
    }

    public ObjectPool(Class<T> clazz, int initPoolSize, int maxPoolSize) {
        this.clazz = clazz;
        this.initPoolSize = initPoolSize;
        this.maxPoolSize = maxPoolSize;
        init(clazz);
    }

    public T get() {
        if (POOL.size() > 0) {
            return POOL.remove(0);
        } else {
            return ReflectUtil.newInstance(clazz);
        }
    }

    public void ret(T t) {
        if (POOL.size() < maxPoolSize) {
            POOL.add(t);
        }
    }
}

/*abstract class BasePool<T> {
    private int initPoolSize = 10;
    private int maxPoolSize = 100;
    private final List<T> pool = Collections.synchronizedList(new LinkedList<>());
    private final Class<T> clazz = (Class<T>) ClassUtil.getTypeArgument(this.getClass());

    public BasePool() {
        init();
    }

    public BasePool(int initPoolSize, int maxPoolSize) {
        this.initPoolSize = initPoolSize;
        this.maxPoolSize = maxPoolSize;
        init();
    }

    private void init() {
        for (int i = 0; i < initPoolSize; i++) {
            pool.add(ReflectUtil.newInstance(clazz));
        }
    }

    protected T get() {
        if (pool.size() > 0) {
            return pool.remove(0);
        } else {
            return ReflectUtil.newInstance(clazz);
        }
    }

    protected void ret(T t) {
        if (pool.size() < maxPoolSize) {
            pool.add(t);
        }
    }
}

class BulletsPool extends BasePool<Bullet> {
    private static final BulletsPool INSTANCE = new BulletsPool();

    private BulletsPool() {
    }

    private BulletsPool(int initPoolSize, int maxPoolSize) {
        super(initPoolSize, maxPoolSize);
    }

    public static BulletsPool getInstance() {
        return INSTANCE;
    }
}*/
